package yjpay.mobile.web.control;

import java.util.ResourceBundle;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import yjpay.URIList.PayAPIURIList;

import com.alibaba.fastjson.JSON;
import com.util.common.RandomUtil;
import com.util.encrypt.AES;
import com.util.encrypt.EncryUtil;
import com.util.encrypt.RSA;

/**
 * 网页支付接口调用示例(返回wap收银台)
 * 
 * @author junqinghuang
 * 
 */
@Controller
public class MobilePayWebCtrl {

	private ResourceBundle resb1 = ResourceBundle.getBundle("payapi");

	// 从配置文件读取易宝分配的公钥
	private String yibaoPublicKey = resb1.getString("payapi.paytest_yibao_publickey");

	// 从配置文件读取商户自己的私钥
	private String merchantPrivateKey = resb1.getString("payapi.paytest_merchant_privatekey");

	// 商户自己随机生成的AESkey
	private String merchantAesKey = RandomUtil.getRandom(16);

	// 商户账户编号
	private String merchantaccount = resb1.getString("payapi.paytest_merchantaccount");

	// 从配置文件读取支付API接口URL前缀
	private String urlPrefix = resb1.getString("payapi.pay_urlprefix");

	@RequestMapping(value = "/pay/to_mobile_pay")
	public ModelAndView home(HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView();
		String default_orderid = "12345" + Math.random() * 30;
		String default_identityid = "user_" + Math.random() * 99900;
		modelAndView.addObject("default_orderid", default_orderid);
		modelAndView.addObject("default_identityid", default_identityid);
		modelAndView.addObject("default_ip", this.getRemoteIP(request));
		modelAndView.addObject("default_userua",  request.getHeader("user-agent"));
		modelAndView.setViewName("pay/mobile_pay.jsp");
		return modelAndView;
	}
	
	@RequestMapping(value = "/pay/to_mobile_pay_credit")
	public ModelAndView toCredit(HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView();
		String default_orderid = "12345" + Math.random() * 30;
		String default_identityid = "user_" + Math.random() * 99900;
		modelAndView.addObject("default_orderid", default_orderid);
		modelAndView.addObject("default_identityid", default_identityid);
		modelAndView.addObject("default_ip", this.getRemoteIP(request));
		modelAndView.addObject("default_userua",  request.getHeader("user-agent"));
		modelAndView.setViewName("pay/mobile_pay_credit.jsp");
		return modelAndView;
	}
	
	@RequestMapping(value = "/pay/to_mobile_pay_debit")
	public ModelAndView toDebit(HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView();
		String default_orderid = "12345" + Math.random() * 30;
		String default_identityid = "user_" + Math.random() * 99900;
		modelAndView.addObject("default_orderid", default_orderid);
		modelAndView.addObject("default_identityid", default_identityid);
		modelAndView.addObject("default_ip", this.getRemoteIP(request));
		modelAndView.addObject("default_userua",  request.getHeader("user-agent"));
		modelAndView.setViewName("pay/mobile_pay_debit.jsp");
		return modelAndView;
	}

	/**
	 * 
	 * 网页支付（通用，储蓄卡+信用卡）
	 * 
	 */
	@RequestMapping(value = "/pay/mobile_pay")
	public ModelAndView mobilepay(Model model,
			@RequestParam("pay_amount") int amount,
			@RequestParam("pay_orderid") String orderid,
			@RequestParam("pay_identityid") String identityid,
			@RequestParam("pay_identitytype") int identitytype,
			@RequestParam("pay_userip") String userip,
			@RequestParam("pay_other") String other,
			@RequestParam("pay_productcatalog") String productcatalog,
			@RequestParam("pay_productname") String productname,
			@RequestParam("pay_productdesc") String productdesc,
			@RequestParam("pay_userua") String userua,
			@RequestParam("pay_callbackurl") String callbackurl,
			@RequestParam("pay_fcallbackurl") String fcallbackurl,
			HttpServletRequest request) throws Exception {

		int currency = 156;
		long i = System.currentTimeMillis() / 1000;
		System.out.println("time:" + i);
		Integer transtime = (int) i;

		TreeMap<String, Object> map = new TreeMap<String, Object>();
		map.put("merchantaccount", merchantaccount);
		map.put("amount", amount);
		map.put("currency", currency);
		map.put("identityid", identityid);
		map.put("identitytype", identitytype);
		map.put("orderid", orderid);
		map.put("other", other);
		map.put("productcatalog", productcatalog);
		map.put("productdesc", productdesc);
		map.put("productname", productname);
		map.put("transtime", transtime);
		map.put("userip", userip);
		map.put("callbackurl", callbackurl);
		map.put("fcallbackurl", fcallbackurl);
		map.put("userua", userua);
		map.put("paytypes", "1|2|3|4");

		// 生成RSA签名
		String sign = EncryUtil.handleRSA(map, merchantPrivateKey);

		map.put("sign", sign);

		// 生成data
		String info = JSON.toJSONString(map);
		System.out.println("业务数据明文：" + info);
		String data = AES.encryptToBase64(info, merchantAesKey);
		System.out.println("含有签名的业务数据密文data:" + data);

		// 使用RSA算法将商户自己随机生成的AESkey加密
		String encryptkey = RSA.encrypt(merchantAesKey, yibaoPublicKey);
		System.out.println("encryptkey:" + encryptkey);

		String mobilePayUrl = urlPrefix+ PayAPIURIList.PAYAPI_MOBILE_PAY.getValue();

		// 浏览器重定向,发送get方式请求，访问一键支付网页支付地址
		// return "redirect:" + mobilePayUrl + "?" + "merchantaccount="
		// + URLEncoder.encode(merchantaccount, "UTF-8") + "&data="
		// + URLEncoder.encode(data, "UTF-8") + "&encryptkey="
		// + URLEncoder.encode(encryptkey, "UTF-8");

		// 通过页面发送post请求，访问一键支付网页支付地址
		// 使用post方式访问一键支付网页支付地址，可以防止被钓鱼，所以请尽量使用post方式
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("mobilePayUrl", mobilePayUrl);
		modelAndView.addObject("merchantaccount", merchantaccount);
		modelAndView.addObject("data", data);
		modelAndView.addObject("encryptkey", encryptkey);
		modelAndView.setViewName("pay/to_yijian_mobile_pay.jsp");
		return modelAndView;

	}
	
	/**
	 * 网页支付（信用卡）
	 */
	@RequestMapping(value = "/pay/mobile_pay_credit")
	public ModelAndView mobileCreditPay(Model model,
			@RequestParam("pay_amount") int amount,
			@RequestParam("pay_orderid") String orderid,
			@RequestParam("pay_identityid") String identityid,
			@RequestParam("pay_identitytype") int identitytype,
			@RequestParam("pay_userip") String userip,
			@RequestParam("pay_other") String other,
			@RequestParam("pay_productcatalog") String productcatalog,
			@RequestParam("pay_productname") String productname,
			@RequestParam("pay_productdesc") String productdesc,
			@RequestParam("pay_userua") String userua,
			@RequestParam("pay_callbackurl") String callbackurl,
			@RequestParam("pay_fcallbackurl") String fcallbackurl,
			HttpServletRequest request) throws Exception {

		int currency = 156;
		long i = System.currentTimeMillis() / 1000;
		System.out.println("time:" + i);
		Integer transtime = (int) i;

		TreeMap<String, Object> map = new TreeMap<String, Object>();
		map.put("merchantaccount", merchantaccount);
		map.put("amount", amount);
		map.put("currency", currency);
		map.put("identityid", identityid);
		map.put("identitytype", identitytype);
		map.put("orderid", orderid);
		map.put("other", other);
		map.put("productcatalog", productcatalog);
		map.put("productdesc", productdesc);
		map.put("productname", productname);
		map.put("transtime", transtime);
		map.put("userip", userip);
		map.put("callbackurl", callbackurl);
		map.put("fcallbackurl", fcallbackurl);
		map.put("userua", userua);
		map.put("paytypes", "1|2|3|4");

		// 生成RSA签名
		String sign = EncryUtil.handleRSA(map, merchantPrivateKey);

		map.put("sign", sign);

		// 生成data
		String info = JSON.toJSONString(map);
		System.out.println("业务数据明文：" + info);
		String data = AES.encryptToBase64(info, merchantAesKey);
		System.out.println("含有签名的业务数据密文data:" + data);

		// 使用RSA算法将商户自己随机生成的AESkey加密
		String encryptkey = RSA.encrypt(merchantAesKey, yibaoPublicKey);
		System.out.println("encryptkey:" + encryptkey);

		String mobilePayUrl = urlPrefix+ PayAPIURIList.PAYAPI_MOBILE_PAY_CREDIT.getValue();

		// 浏览器重定向,发送get方式请求，访问一键支付网页支付地址
		// return "redirect:" + mobilePayUrl + "?" + "merchantaccount="
		// + URLEncoder.encode(merchantaccount, "UTF-8") + "&data="
		// + URLEncoder.encode(data, "UTF-8") + "&encryptkey="
		// + URLEncoder.encode(encryptkey, "UTF-8");

		// 通过页面发送post请求，访问一键支付网页支付地址
		// 使用post方式访问一键支付网页支付地址，可以防止被钓鱼，所以请尽量使用post方式
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("mobilePayUrl", mobilePayUrl);
		modelAndView.addObject("merchantaccount", merchantaccount);
		modelAndView.addObject("data", data);
		modelAndView.addObject("encryptkey", encryptkey);
		modelAndView.setViewName("pay/to_yijian_mobile_pay.jsp");
		return modelAndView;

	}
	
	/**
	 * 网页支付（储蓄卡）
	 */
	@RequestMapping(value = "/pay/mobile_pay_debit")
	public ModelAndView mobileDebitPay(Model model,
			@RequestParam("pay_amount") int amount,
			@RequestParam("pay_orderid") String orderid,
			@RequestParam("pay_identityid") String identityid,
			@RequestParam("pay_identitytype") int identitytype,
			@RequestParam("pay_userip") String userip,
			@RequestParam("pay_other") String other,
			@RequestParam("pay_productcatalog") String productcatalog,
			@RequestParam("pay_productname") String productname,
			@RequestParam("pay_productdesc") String productdesc,
			@RequestParam("pay_userua") String userua,
			@RequestParam("pay_callbackurl") String callbackurl,
			@RequestParam("pay_fcallbackurl") String fcallbackurl,
			HttpServletRequest request) throws Exception {

		int currency = 156;
		long i = System.currentTimeMillis() / 1000;
		System.out.println("time:" + i);
		Integer transtime = (int) i;

		TreeMap<String, Object> map = new TreeMap<String, Object>();
		map.put("merchantaccount", merchantaccount);
		map.put("amount", amount);
		map.put("currency", currency);
		map.put("identityid", identityid);
		map.put("identitytype", identitytype);
		map.put("orderid", orderid);
		map.put("other", other);
		map.put("productcatalog", productcatalog);
		map.put("productdesc", productdesc);
		map.put("productname", productname);
		map.put("transtime", transtime);
		map.put("userip", userip);
		map.put("callbackurl", callbackurl);
		map.put("fcallbackurl", fcallbackurl);
		map.put("userua", userua);
		map.put("paytypes", "1|2|3|4");

		// 生成RSA签名
		String sign = EncryUtil.handleRSA(map, merchantPrivateKey);

		map.put("sign", sign);

		// 生成data
		String info = JSON.toJSONString(map);
		System.out.println("业务数据明文：" + info);
		String data = AES.encryptToBase64(info, merchantAesKey);
		System.out.println("含有签名的业务数据密文data:" + data);

		// 使用RSA算法将商户自己随机生成的AESkey加密
		String encryptkey = RSA.encrypt(merchantAesKey, yibaoPublicKey);
		System.out.println("encryptkey:" + encryptkey);

		String mobilePayUrl = urlPrefix
				+ PayAPIURIList.PAYAPI_MOBILE_PAY_DEBIT.getValue();

		// 浏览器重定向,发送get方式请求，访问一键支付网页支付地址
		// return "redirect:" + mobilePayUrl + "?" + "merchantaccount="
		// + URLEncoder.encode(merchantaccount, "UTF-8") + "&data="
		// + URLEncoder.encode(data, "UTF-8") + "&encryptkey="
		// + URLEncoder.encode(encryptkey, "UTF-8");

		// 通过页面发送post请求，访问一键支付网页支付地址
		// 使用post方式访问一键支付网页支付地址，可以防止被钓鱼，所以请尽量使用post方式
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("mobilePayUrl", mobilePayUrl);
		modelAndView.addObject("merchantaccount", merchantaccount);
		modelAndView.addObject("data", data);
		modelAndView.addObject("encryptkey", encryptkey);
		modelAndView.setViewName("pay/to_yijian_mobile_pay.jsp");
		return modelAndView;

	}

	public String getRemoteIP(HttpServletRequest request) {
		if (request.getHeader("x-forwarded-for") == null) {
			return request.getRemoteAddr();
		}
		return request.getHeader("x-forwarded-for");
	}

}
